package cn.zyf;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;

public class IdCode {

    /*
     * sql:
     * CREATE DATABASE updatetool CHARACTER SET utf8mb4 COLLATE utf8mb4_bin ENGINE=InnoDB;
     * create table id_code (id int not null auto_increment primary key, day char(8) not null, serial char(4) not null, unique key idx_ds (day, serial));
     * create user 'zyf'@'%' identified by '123456';
     * GRANT SELECT, INSERT, UPDATE, DELETE ON `updatetool`.`id_code` TO 'zyf'@'%';
     * FLUSH PRIVILEGES;
     *
     *
     * id code:
     * 360481[20250101][xxxx]
     */

    private static final String areaCode = "360481";

    public static void main(String[] args) throws Exception {
        new IdCode().run();
    }

    private void run() throws Exception {
        String url = "jdbc:mysql://192.168.1.1:3306/updatetool";
        String username = "zyf";
        String password = "123456";

        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);

        String day = getYYYYMMDD();
        String lastSerial = getLastSerial(connection, day);
        String nextSerial = getNextSerial(lastSerial);
        String newIdCode = String.format("%s%s%s", areaCode, day, nextSerial);

        insertSerial(connection, day, nextSerial);

        System.out.println(newIdCode);

        connection.close();
    }

    private void insertSerial(Connection connection, String day, String nextSerial) throws Exception {
        Statement statement = connection.createStatement();
        String sql = String.format("insert into id_code (day, serial) values ('%s', '%s')", day, nextSerial);
        statement.executeUpdate(sql);
        statement.close();
    }

    private String getLastSerial(Connection connection, String day) throws Exception {

        if (day.length() != 8) {
            throw new RuntimeException(day);
        }

        Statement statement = connection.createStatement();
        String sql = String.format("select * from id_code where day = '%s'", day);
        ResultSet rs = statement.executeQuery(sql);

        String s = "";
        while (rs.next()) {
            String serial = rs.getString("serial");
            if (s.compareTo(serial) < 0) {
                s = serial;
            }
        }


        rs.close();
        statement.close();
        return s;
    }

    private String getNextSerial(String s) {
        if (s.equals("")) {
            s = "0000";
        } else {
            if (s.equals("9999")) {
                throw new RuntimeException(s);
            }
            char[] chars = s.toCharArray();
            StringBuilder builder = new StringBuilder();
            boolean add = true;
            for (int i = 3; i >= 0; i--) {
                if (add) {
                    if (chars[i] == '9') {
                        builder.insert(0, '0');
                    } else {
                        builder.insert(0, (char) (chars[i] + 1));
                        add = false;
                    }
                } else {
                    builder.insert(0, chars[i]);
                }
            }
            s = builder.toString();
        }

        return s;
    }

    private String getYYYYMMDD() {

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        return String.format("%s%s%s", year, month < 10 ? "0" + month : month, day < 10 ? "0" + day : day);
    }

}
